// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var UnitTools = require('UnitTools')
var CreatorHelper = require('CreatorHelper')
var Config = require('Config')
var ClickManager = require('ClickManager')
var NetworkManager = require('NetworkManager')
var UserManager = require('UserManager')

cc.Class({
    extends: cc.Component,

    properties: {
        tid: 0, // 牌桌id
        count: 0,
        token: null,
        config: null, // 牌桌配置
        myselfStatus: 0,
        tableIdString: cc.Label,

        startBtnNode: cc.Node,
        startBtnText: cc.Label,
        startBtnEv: cc.Node,

        // 下拉按钮
        downBtnNode: {
            type: cc.Node,
            default: []
        },
        downMenu: cc.Node,

        // 菜单按钮
        menuBtnNode: {
            type: cc.Node,
            default: []
        },

        // 菜单模态框
        menuModel: {
            type: cc.Prefab,
            default: []
        },

        // 按钮组
        btnGroupNode: cc.Node,
        toolsBtnNode: {
            type: cc.Node,
            default: []
        },

        // 玩家组
        players: {
            type: cc.Node,
            default: []
        },
        playersName: {
            type: cc.Label,
            default: []
        },
        playersBalance: {
            type: cc.Label,
            default: []
        },
        playerBetMoney: {
            type: cc.Label,
            default: []
        },
        playerHandArea: {
            type: cc.Node,
            default: []
        },
        playerReadlyStatus: {
            type: cc.Label,
            default: []
        },

        lowNote: cc.Label, // 低注
        curBetTotal: cc.Label, // 当前投注总额

        cardsList: [], // 发牌列表
        callCardsList: null, // 叫牌列表
        serviceCallCards: null, // 服务器叫牌列表
        outTiemr: 15, // 计时器

        // 时钟
        clockList: {
            type: cc.Node,
            default: []
        },
        clockText: {
            type: cc.Label,
            default: []
        },

        cardPrefab: cc.Prefab,
        alert: cc.Prefab,

        seeStatus: false, // 看牌状态
        callCardStatus: false,
        clockIndex: 0,

        confirmModel: cc.Node, // 确认框
        confirmNode: cc.Node,  // 确认按钮
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.init()
    },

    start () {
        this.schedule(() => {
            if (this.config['gameing']) {
                this.clockText[this.clockIndex].string = this.outTiemr
                if (this.outTiemr <= 0) {
                    this.callCardStatus = false
                    this.gameStartAndStartASteps()
                    return false
                }
                this.outTiemr--
            }
        }, 1)
    },

    onDestroy () {
        console.log('摧毁')
    },

    onEnable () {
    },

    update (dt) {
        this.count++
        if (this.tid != 0) {
            this.getTableConfig()
        }
        this.gameStartAndStartASteps()
    },

    // 显示下拉菜单
    showDownMenu () {
        this.downMenu.active = true
    },

    // 初始化事件
    initEvent () {
        var scene = cc.director.getScene()

        // 下拉
        for (let i in this.downBtnNode) {
            this.downBtnNode[i].i = i
            ClickManager.onClick(this.downBtnNode[i], this, () => {
                let idx = parseInt(this.downBtnNode[i].i)
                if (idx === 0) {
                    this.downBtnNode[idx].active = false
                    this.downBtnNode[1].active = true
                    this.showDownMenu()
                } else {
                    this.downBtnNode[idx].active = false
                    this.downBtnNode[0].active = true
                    this.downMenu.active = false
                }
            })
        }

        // 菜单事情
        for (let i in this.menuBtnNode) {
            this.menuBtnNode[i].i = i
            ClickManager.onClick(this.menuBtnNode[i], this, () => {
                let idx = parseInt(this.menuBtnNode[i].i)
                if (idx === 0) {
                    // 退出房间
                    this.exitRoom()
                } else if (idx === 1) {
                    // 帮助
                    let node = cc.instantiate(this.menuModel[0])
                    node.parent = scene
                    node.active = true
                } else {
                    // 设置
                    let node = cc.instantiate(this.menuModel[1])
                    node.parent = scene
                    node.active = true
                }
            })
        }

        // 工具拦事件
        for (let i in this.toolsBtnNode) {
            this.toolsBtnNode[i].i = i
            ClickManager.onClick(this.toolsBtnNode[i], this, () => {
                let idx = parseInt(this.toolsBtnNode[i].i)
                switch (idx) {
                    case 0:
                        this.toolsACard()
                        break
                    case 1:
                        this.toolsSeeCard()
                        break
                    case 2:
                        this.toolsDisCard()
                        break
                    case 3:
                        this.toolsWithNote()
                        break
                    case 4:
                        this.toolsFilling()
                        break
                    case 5:
                        this.toolsAllIn()
                        break
                }
            })
        }

        // 准备/开始Game
        ClickManager.onClick(this.startBtnEv, this, () => {
            console.log(this.myselfStatus)
            if (this.myselfStatus === 0 || this.myselfStatus === 1) {
                this.gameReadyOrNotReady()
            } else if (this.myselfStatus === 2) {
                this.gameStart()
            }
        })
    },

    // 初始化
    init () {
        this.initEvent()
        if (UnitTools.isNullOrUndefined(UserManager.joinToTableData)) {
            return this.goToHall()
        }

        this.initClock()
        this.tid = UserManager.joinToTableData.tid
        this.tableIdString.string = '房间ID：'+this.tid+' '
        this.token = UserManager.token
        this.initTableInfo()
    },

    // 初始化时钟
    initClock (index) {
        // 默认时钟全部为false
        for (let k in this.clockList) {
            if (k == index) {
                this.clockList[k].active = true
            } else {
                this.clockList[k].active = false
            }
        }
        if (UnitTools.isNullOrUndefined(index)) return false
    },

    // 退出房间
    exitRoom () {
        this.confirmModel.active = true

        // 事件绑定
        ClickManager.onClick(this.confirmNode, this, () => {
            this.confirmModel.active = false
            if (this.config.gameing === true) {
                ClickManager.alertModel(this.alert, '正在游戏中无法退出房间...')
                return false
            }

            NetworkManager.onConnectedToGame( (gameService) => {
                gameService.proxy.exitRoom(this.tid, this.token, (data) => {
                    if (data.ok && data.code === 200) {
                        this.goToHall()
                    } else {
                        ClickManager.alertModel(this.alert, data.msg)
                    }
                })
            })
        })
    },

    // 游戏准备\取消准备
    gameReadyOrNotReady () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.gameReadyOrNot(this.token, this.tid, (data) => {
                if (data.ok && data.code === 200) {
                    this.getTableConfig()
                } else {
                    ClickManager.alertModel(this.alert, data.msg)
                }
            })
        })
    },

    // 开始游戏
    gameStart () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.gameStart(this.tid, (data) => {
                if (data.ok && data.code === 200) {
                    this.getTableConfig()
                    this.getLicensingToHand()
                } else {
                    ClickManager.alertModel(this.alert, data.msg)
                }
            })
        })
    },

    // 发手牌
    getLicensingToHand () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.sendLicensingToHand(this.tid, (data) => {
                if (data.ok && data.code === 200) {
                    this.getTableConfig()
                }
            })
        })
    },

    // 初始化牌桌信息
    initTableInfo () {
        try {
            NetworkManager.onConnectedToGame( (gameService) => {
                gameService.proxy.initTableInfo(this.tid, (data) => {
                    this.getTableConfig()
                })
            } )
        } catch (err) {
            this.goToHall()
        }
    },

    // 错误返回大厅
    goToHall () {
        cc.director.loadScene('hall')
    },

    // 获取牌桌配置
    getTableConfig () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.getConfig(this.token, this.tid, (data) => {
                if (data.ok && data.code === 200) {
                    this.config = JSON.parse(data.datas)
                    this.setTableConfig()
                }
            })
        })
    },

    // 设置牌桌配置
    setTableConfig () {
        this.setUserConfig()
        this.startBtnNode.active = true

        // 设置低注
        this.lowNote.string = this.config.config.low_grade+' '

        // 设置游戏状态
        if (this.config.gameing === true) {
            this.startBtnNode.active = false // 游戏已经开始
        }
    },

    // 设置玩家状态
    setUserConfig () {
        var betTotal = 0
        var index = 0
        for (let i in this.config['user']) {
            let info = this.config['user'][i]

            if (parseInt(info.uid) == parseInt(this.config.selfid) &&
                !this.config.gameing) {
                this.myselfStatus = info['status']
                if (info['status'] === 0) {
                    this.startBtnText.string = '准 备'
                } else if (info['status'] === 1) {
                    this.startBtnText.string = '已准备'
                } else if (info['status'] === 2) {
                    this.startBtnText.string = '开始游戏'
                }
            }

            betTotal += info['bet_balance']
            this.players[index].active = true
            this.setPlayerInfo(info, index)
            this.cradsArea(info, index)
            index++
        }
        this.curBetTotal.string = betTotal+' '
    },

    // 设置玩家信息
    setPlayerInfo (info, idx) {
        this.players[idx].active = true
        this.playersName[idx].string = info['username']
        this.playersBalance[idx].string = info['balance']+' '
        this.playerBetMoney[idx].string = info['bet_balance']+' '
        if (this.config['gameing']) {
            this.playerReadlyStatus[idx].string = ''
        } else {
            if (info['status'] === 0) {
                this.playerReadlyStatus[idx].string = '   未准备'
            } else if (info['status'] === 1) {
                this.playerReadlyStatus[idx].string = '   已准备'
            } else if (info['status'] === 2) {
                this.playerReadlyStatus[idx].string = '   房主'
            }
        }
    },

    // 游戏开始，创建叫牌流程
    gameStartAndStartASteps () {
        if (UnitTools.isNullOrUndefined(this.config)) {
            return false
        }
        if (!this.config['gameing']) {
            return false;
        }
        if (this.callCardStatus) {
            return false;
        }

        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.startCallCrads(this.tid, '', (data) => {
                if (data.ok && data.code === 200) {
                    let obj = JSON.parse(data.datas)
                    this.callCardsList = obj.call
                    this.outTiemr = obj.down
                    this.saveCallService()
                    this.callCardStatus = true
                }
            })
        })
    },

    // 开始叫牌
    startCallCrads () {
        this.btnGroupNode.active = false
        var maxId = 0, index = 0
        for (let i in this.callCardsList) {
            let call = this.callCardsList[i]
            if (call.maxCount) {
                if (call.uid == this.config.selfid)
                    this.btnGroupNode.active = true
                maxId = call.uid
            }
        }
        for (let k in this.config['user']) {
            if (maxId == this.config['user'][k]['uid']) {
                break
            }
            index++
        }

        this.clockIndex = index
        this.initClock(index)
    },

    // 叫牌数据保存service
    saveCallService () {
        var tempList = [],
            maxUid = '',
            callList = []

        if (!UnitTools.isNullOrUndefined(this.callCardsList) &&
            this.callCardsList.length != 0) {
            tempList = UnitTools.objSort(this.callCardsList)
        } else {
            return false
        }

        for (let i in tempList) {
            maxUid = tempList[i].uid
            break;
        }
        if (maxUid === '') return false
        this.startCallCrads()
    },

    // 制作牌区域
    cradsArea (info, idx) {
        this.cardsList[info['uid']] = UnitTools.isNullOrUndefined(this.cardsList[info['uid']])
            ? [] : this.cardsList[info['uid']]

        for (let k in this.config['pos']) {
            if (!UnitTools.isNullOrUndefined(k) &&
                info['uid'] == k &&
                this.config['pos'][k].length > this.playerHandArea[idx].childrenCount) {

                let kvalue  = this.config['pos'][k]
                let clength = this.playerHandArea[idx].childrenCount
                for (let i = clength; i < this.config['pos'][k].length; i++) {
                    for (let ck in kvalue[i]) {
                        let obj = {
                            card: ck,
                            status: kvalue[i][ck]
                        }
                        this.cardsList[k].push(obj)

                        // 复制牌区域
                        let node = cc.instantiate(this.cardPrefab)
                        this.playerHandArea[idx].addChild(node)
                        node.getComponent('CardBuild').init(obj)
                    }
                }
            }
        }
    },

    // 比较牌面大小
    compareShowCradSize () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.compareSize(this.tid, (data) => {
                console.log(data)
                if (data.ok && data.code === 200) {
                    this.getTableConfig()
                }
            })
        })
    },

    // 过牌
    toolsACard () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.aCrads(this.tid, this.token, (data) => {
                console.log("过牌:", data)
                if (data.ok && data.code === 200) {
                    this.getTableConfig()
                }
            })
        })
    },

    // 看牌
    toolsSeeCard () {
        let index = 0
        for (let k in this.config['user']) {
            let info = this.config['user'][k]
            if (info['uid'] == this.config.selfid) {
                let obj = {
                    card: Object.keys(this.config['pos'][k][0])[0],
                    status: !this.seeStatus
                }
                this.seeStatus = obj.status

                let childNode = this.playerHandArea[index].children
                childNode[0].getComponent('CardBuild').init(obj)
                break
            }
            index++
        }
    },

    // 弃牌
    toolsDisCard () {
        let index = 0
        for (let k in this.config['user']) {
            let info = this.config['user'][k]
            if (info['uid'] == this.config.selfid) {
                let obj = {
                    card: 0,
                    status: false
                }
                let childNode = this.playerHandArea[index].children
                for (let key in childNode) {
                    childNode[key].getComponent('CardBuild').init(obj)
                }
                break
            }
            index++
        }

        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.disCrads(this.tid, this.token, (data) => {
                if (data.ok && data.code === 200) {
                    console.log('弃牌:', data)
                    this.getTableConfig()
                }
            })
        })
    },

    // 跟注
    toolsWithNote () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.withNote(this.tid, this.token, (data) => {
                if (data.ok && data.code === 200) {
                    console.log('跟注:', data)
                    this.getTableConfig()
                }
            })
        })
    },

    // 加注
    toolsFilling () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.filling(this.tid, this.token, 2, (data) => {
                if (data.ok && data.code === 200) {
                    console.log('加注:', data)
                    this.getTableConfig()
                }
            })
        })
    },

    // 梭哈
    toolsAllIn () {
        NetworkManager.onConnectedToGame( (gameService) => {
            gameService.proxy.allIn(this.tid, this.token, (data) => {
                if (data.ok && data.code === 200) {
                    console.log('梭哈:', data)
                    this.getTableConfig()
                }
            })
        })
    },
});
